<template>
  <div>
    <UploadExcel :on-success="onSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { subject } from '@/api/subject.js'
import UploadExcel from '@/components/lib/uploadExcel.vue'
export default {
  components: {
    UploadExcel
  },
  methods: {
    async onSuccess(res) {
      console.log(res)
      const newArr = res.results.map(item => {
        return {
          rid: item['学科编号'],
          name: item['学科名称'],
          short_name: item['学科简称'],
          username: item['创建者'],
          create_time: item['创建日期']
        }
      })
      console.log('参数', newArr)
      for (let i = 0; i < newArr.length; i++) {
        await subject(newArr[i])
      }
      this.$message.success('导入学科成功')
      this.$router.push('/subjectlist')
    },
    beforeUpload(res) {
      console.log('上传前', res)
      // 限制在2mb以内
      const limit2mb = res.size / 1024 / 1024 < 2
      if (!limit2mb) {
        this.$message.error('请上传2mb以内文件')
      }
      // 限制只能上传excel格式
      const limitType = /\.(xlsx|xls|csv)$/.test(res.name)
      if (!limitType) {
        this.$message.error('请上传xlsx|xls|csv格式的文件')
      }
      return limit2mb && limitType
    }
  }
}
</script>

<style>

</style>
